<template>
  <div class="container">
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1', '3']" style="border-right: none">
          <div class="head-container">
            <el-input
              v-model="filterText"
              prefix-icon="el-icon-search"
              size="small"
              placeholder="请输入部门名称"
              style="margin: 20px 0 20px 0"
              clearable
            />
          </div>
          <div class="head-container">
            <el-tree
              ref="tree"
              node-key="id"
              class="filter-tree"
              :data="deptData"
              :props="defaultProps"
              default-expand-all
              :filter-node-method="filterNode"
              :is-disabled="flagStatus"

              @node-click="getNodes"
            />
          </div>
        </el-menu>
      </el-aside>
      <el-container>
        <el-main>
          <el-form
            v-show="showSearch"
            ref="queryForm"
            :inline="true"
            :model="formInline"
            size="small"
            class="demo-form-inline"
          >
            <el-form-item label="用户昵称">
              <el-input
                v-model="formInline.userName"
                placeholder="请输入用户昵称"
                clearable
              />
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input
                v-model="formInline.phonenumber"
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="formInline.status"
                placeholder="用户状态"
                clearable
                style="width: 240px"
              >
                <el-option label="正常" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="formInline.createTime"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
              >新增
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate(false, null)"
              >修改
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
              >删除
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
              >导入
              </el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
              >导出
              </el-button>
            </el-col>
            <right-toolbar :show-search.sync="showSearch" @queryTable="loadUsersList" />
          </el-row>

          <el-table
            ref="multipleTable"
            v-loading="loading"
            :data="userList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" :selectable="selectHandle" />
            <el-table-column label="用户编号" prop="userId" width="120" />
            <el-table-column label="用户名称" prop="userName" width="120" />
            <el-table-column label="用户昵称" prop="nickName" width="120" />
            <el-table-column label="部门" prop="deptName" width="120" />
            <el-table-column label="手机号码" prop="phonenumber" width="120" />
            <el-table-column label="状态" align="center">
              <template slot-scope="scope">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :disabled="!(scope.row.userName === currUser)"
                  content="当前登录用户禁止停用！"
                  placement="top"
                >
                  <el-switch
                    v-model="scope.row.status"
                    :disabled="scope.row.userName === currUser"
                    active-value="0"
                    inactive-value="1"
                    @change="handleStatusChange(scope.row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding " width="200px">
              <template v-if="scope.row.userId !== 1" slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(true,scope.row)">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
                </el-button>
                <el-dropdown trigger="click" size="mini">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-d-arrow-right el-icon--right"
                    @click="handleMore(scope.row)"
                  >更多
                  </el-button>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-key" @click.native="updatePassword(scope.row)">重置密码</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-circle-check" @click.native="allocation(scope.row )">分配角色
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </el-table-column>
          </el-table>

          <!--          分页 开始-->
          <el-pagination
            :current-page="current"
            :page-sizes="[2, 5, 10, 20, 40]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <!--表格数据-->
          <el-dialog :title="this.formTile" :visible.sync="dialogFormVisible">
            <el-form ref="userForm" :model="userForm" label-width="80px" :rules="rules" class="demo-ruleForm">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="用户昵称" style=" display: inline-block;width:300px" prop="nickName">
                    <el-input v-model="userForm.nickName" placeholder="请输入用户" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="用户性别" style="display: inline-block;margin-left: 50px;width:350px">
                    <el-select v-model="userForm.sex" placeholder="请选择性别">
                      <el-option label="男" value="0" />
                      <el-option label="女" value="1" />
                      <el-option label="未知" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="归属部门" style="width:650px" prop="parentId">
                <treeselect
                  v-model="userForm.deptId"
                  placeholder="请选择部门"
                  :options="menuOptions"
                  :normalizer="normalizer"
                  :show-count="true"
                />
              </el-form-item>

              <el-form-item label="手机号码" style="display: inline-block;width:300px" prop="phonenumber">
                <el-input v-model="userForm.phonenumber" placeholder="请输入联系电话" />
              </el-form-item>
              <el-form-item label="邮箱" style="display: inline-block;margin-left: 50px;width:300px" prop="email">
                <el-input v-model="userForm.email" placeholder="请输入邮箱" />
              </el-form-item>
              <el-row>
                <el-col :span="12">
                  <el-form-item v-if="userForm.userId == '-1'" label="用户名称" style="display: inline-block;width:300px" prop="userName">
                    <el-input v-model="userForm.userName" placeholder="请输入用户名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item v-if="userForm.userId == '-1'" label="用户密码" style="display: inline-block;margin-left: 50px;width:300px" prop="password">
                    <el-input v-model="userForm.password" show-password />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="岗位" style="display: inline-block;margin-left: 50px;width:350px">
                    <el-select v-model="userForm.post" placeholder="请选择岗位">
                      <el-option v-for="(item, index) in postData" :key="index" :label="item.postName" :value="item.postId" />
                      <!--                      <el-option label="董事长" value="0" />-->
                      <!--                      <el-option label="项目经理" value="1" />-->
                      <!--                      <el-option label="人力资源" value="2" />-->
                      <!--                      <el-option label="普通员工" value="3" />-->
                    </el-select>
                  </el-form-item>

                </el-col>
                <el-col :span="12">
                  <el-form-item label="角色" style="display: inline-block;margin-left: 50px;width:350px">
                    <el-select
                      v-model="userForm.roleIds"
                      multiple
                      filterable
                      allow-create
                      default-first-option
                      placeholder="请选择角色"
                    >
                      <el-option v-for="(item,index) in sysRoleList" :key="index" :label="item.roleName" :value="item.roleId" />
                      <!--                  <el-option label="普通角色" value="1"></el-option>-->
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row>
                <el-col :span="12">
                  <el-form-item label="状态" style="display: inline-block">
                    <el-radio-group v-model="userForm.status">
                      <el-radio label="0" value="0">正常</el-radio>
                      <el-radio label="1" value="1">停用</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="备注" style="display: inline-block;margin-left: 140px" prop="remark">
                    <el-input v-model="userForm.remark" type="textarea" placeholder="请输入内容" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="save('userForm')">确定</el-button>
              <el-button type="danger" @click="resetForm('userForm')">关闭</el-button>
            </div>
          </el-dialog>

          <!-- 用户导入对话框 -->
          <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
              ref="upload"
              :limit="1"
              accept=".xlsx, .xls"
              :action="upload.url"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :auto-upload="false"
              drag
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div slot="tip" class="el-upload__tip text-center">
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link
                  type="primary"
                  :underline="false"
                  style="font-size:12px;vertical-align: baseline;"
                  @click="importTemplate"
                >下载模板
                </el-link>
              </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import { parseTime } from '../../../utils'
import { getToken } from '../../../utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import * as router from 'vue-router'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getInfo } from '../../../api/user'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { checkInfo } from '@/api/user'
import store from '@/store'

export default {
  name: 'Index',
  components: { Treeselect },
  data() {
    const validatePhone = (rule, value, callback) => {
      console.log(value)
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      const reg = '*'
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (!regMobile.test(value) && reg !== (value.slice(4, 5))) {
        callback(new Error('手机号码不正确!'))
      } else {
        callback()
      }
    }
    const validateName = async(rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        const res = await checkInfo(value)
        if (res.data) {
          callback(new Error('用户名已存在'))
        } else {
          callback()
        }
      }
    }
    return {
      rules: {
        nickName: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在1到 5 个字符', trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, validator: validatePhone, trigger: 'change' },
          { min: 11, max: 11, message: '手机号长度不正确！', trigger: ['blur', 'change'] }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 5, max: 10, message: '长度在5到 10 个字符', trigger: ['blur', 'change'] }
        ],
        userName: [
          { required: true, validator: validateName, trigger: 'blur' },
          { min: 1, max: 5, message: '长度在1到 5 个字符', trigger: 'blur' }
        ]
      },
      currUser: store.getters.name,
      refreshTable: true,
      isExpandAll: false,
      statusOptions: [], // 状态选项
      loading: true, // 遮罩层
      ids: [], // 选中数组
      single: true, // 非单个禁用
      multiple: true, // 非多个禁用
      showSearch: true, // 显示搜索条件
      filterText: '', // 搜索部门名称
      title: '',
      value1: '', // 时间
      userList: [], // 用户数据
      current: 1, // 当前页数
      size: 5, // 当前条数
      total: 5, // 总条数
      userForm: {
        userId: '-1',
        nickName: '',
        deptId: '',
        phoneNumber: '',
        email: '',
        createBy: '',
        userName: '',
        password: '123456',
        status: '0',
        remark: '',
        roleIds: [],
        sysRoles: []
      },
      dialogFormVisible: false,
      menuOptions: [],
      formTile: '',
      formInline: {
        userId: '',
        userName: '',
        phonenumber: '',
        status: '',
        ceateTime: '',
        deptId: ''
      },
      deptFlag: '',
      flagStatus: false,

      deptData: [], // 部门树形数据
      postData: [], // 岗位信息
      defaultProps: {
        children: 'depts',
        label: 'deptName',
        disabled: function(data, node) {
          console.log(data)
          console.log(node)
          if (data.status == 1) {
            this.flagStatus = true
          }
        }
      },

      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: '/sysUser/import?Authorization=' + getToken()
      },
      sysRoleList: [],
      selectUserData: {}
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }

  },
  created() {
    this.queryPostBaseData()
    this.getDeptTreeData()
    this.loadUsersList(this.current)
  },

  methods: {

    // 获取当前节点信息(左侧菜单与分页显示联动)
    getNodes(node, e) {
      this.formInline.deptId = node.deptId
      this.formInline.userId = ''
      this.loading = true
      // 分页数据
      this.axios.get('/sysUser/page?' + this.qs.stringify(this.formInline),
        {
          params: {
            current: this.current,
            size: this.size
          }
        }).then(result => {
        // 处理后台数据(将后台result.data数据与userList集合绑定)
        this.userList = result.data.data.records
        this.total = result.data.data.total
      })

      this.loading = false
    },

    getDeptTreeData() {
      // 新增 菜单树 数据
      this.axios.get('/sysDept/deptTree/', {
        params: this.formInline
      }).then(res => {
        this.deptData = res.data.data
        this.menuOptions = res.data.data
      })
    },

    // 查询岗位信息
    queryPostBaseData() {
      const params = {
        'status': 0
      }
      this.axios.post('/sysPost/condition?current=1&size=99999', params).then(res => {
        if (res.data.status == 'OK') {
          this.postData = res.data.data.records
        }
      })
    },

    // 左侧部门树的显示
    filterNode(value, data) {
      if (!value) return true
      return data.deptName.indexOf(value) !== -1
    },

    // 转换树结构
    normalizer(node) {
      if (node.depts && !node.depts.length) {
        delete node.depts
      }
      if (node.deptName == null) {
        node.deptName = '请选择部门'
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.depts

      }
    },
    // 折叠菜单
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    // 修改(数据回显)
    handleUpdate(flag, row) {
      console.log('修改用户信息====>', row)
      this.querySysRoleList()
      this.reset()
      this.dialogFormVisible = true
      this.formTile = '修改用户'
      this.userForm.updateBy = this.userName
      // this.userForm.parentId = row.deptId
      if (flag) {
        this.userForm = this.qs.parse(this.qs.stringify(row)) // 将row对象解析后赋值给表单对象
        console.log('修改爱就爱==>', this.userForm)
      } else {
        this.userForm = this.selectUserData
      }
    },
    handleAdd() {
      this.formTile = '添加用户'
      this.querySysRoleList()
      this.dialogFormVisible = true
    },

    // 加载页面数据
    async loadUsersList(current) {
      this.loading = true
      // const res = await getInfo(getToken())
      // this.formInline.userId = res.data.info.userId
      console.log(this.formInline)
      // 分页数据
      this.axios.get('/sysUser/page?' + this.qs.stringify(this.formInline),
        {
          params: {
            current: this.current,
            size: this.size
          }
        }).then(result => {
        // 处理后台数据(将后台result.data数据与userList集合绑定)
        this.userList = result.data.data.records
        this.total = result.data.data.total
      })

      this.loading = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.loadUsersList(this.current)
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.formInline = {
        userName: '',
        phonenumber: '',
        status: '',
        ceateTime: ''
      }
      this.handleQuery()
    },

    // 保存按钮
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 新增
          if (this.userForm.userId == -1) {
            // 新增
            this.userForm.userId = ''
            this.axios.post('/sysUser/add', this.userForm).then(result => {
              if (result.data.data == '添加成功') {
                this.$message({
                  message: '添加成功',
                  type: 'success',
                  duration: 2000 // 显示时间, 毫秒。

                })
                this.resetForm(formName)
                this.loadUsersList(this.current) // 加载页面
              }
            })
          } else {
            // 修改
            this.userForm.password = ''
            this.userForm.sysRoles = []
            if (!this.userForm.roleIds) {
              this.userForm.roleIds = []
            }
            this.axios.post('/sysUser/update', this.userForm).then(result => {
              if (result.data.data == '修改成功') {
                this.$message({
                  message: '修改成功',
                  type: 'success',
                  duration: 2000 // 显示时间, 毫秒。
                })

                this.loadUsersList(this.current) // 加载页面
              }
            })
          }
          // 清除表单数据
          this.clear()
          // 关闭表单
          this.dialogFormVisible = false
        }
      })
    },
    // 关闭表单
    resetForm(userForm) {
      // 清空规则
      this.$refs.userForm.clearValidate()
      this.dialogFormVisible = false
      this.clear()
    },
    clear() {
      this.userForm = {
        userId: '-1',
        nickName: '',
        deptId: '0',
        parentId: '0',
        phoneNumber: '',
        email: '',
        createBy: '',
        userName: '',
        password: '',
        status: '0',
        remark: '',
        roleId: ''
      }
    },

    // 更多
    handleMore() {

    },
    // 角色状态修改
    async handleStatusChange(row) {
      if (row.userName === store.getters.name && row.status === '1') {
        this.$message.error('当前登录用户禁止停用！')
      } else {
        const text = row.status == '0' ? '启用' : '停用'
        this.userForm = row
        const { data: res } = await this.axios.post('/sysUser/update', this.userForm)
        if (res.status !== 'OK') {
          return this.$message.error('失败')
        }
        this.$message.success(text + '成功')
      }
    },
    // 模糊查询提交按钮
    onSubmit() {
      this.loading = true
      // 将日期转换为字符串
      if (this.value1[0] != null) {
        this.formInline.startTime = parseTime(this.value1[0]).slice(0, 10)
        this.formInline.endTime = parseTime(this.value1[1]).slice(0, 10)
      }

      this.loadUsersList(this.current)
      this.value1 = ''
    },
    // 重置按钮
    reset() {
      this.formInline = {
        UserName: '',
        phonenumber: '',
        status: '',
        createTime: '',
        deptId: ''
      },
      this.value1 = ''
    },
    handleSizeChange(val) {
      this.size = val
      this.loadUsersList(this.current)
    },
    handleCurrentChange(val) {
      this.current = val
      this.loadUsersList(this.current)
    },

    // 导出
    handleExport() {
      window.open('http://localhost:8080/sysUser/export?Authorization=' + getToken(), '_parent')
    },
    /* 格式化时间*/
    parseTime(time) {
      var date = new Date(time)
      return parseTime(date)
    },
    //
    allocation(row) {
      this.$router.push('/system/user/role/' + row.userId)
    },
    updatePassword(row) {
      this.$confirm('是否确认重置密码？ 密码为123456', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.axios.put('http://localhost:8080/sysUser/updatePassword').then(res => {
            this.loadUsersList(this.current)
            this.$message({

              type: 'success',
              message: '重置成功'
            })
          })
        })
        .catch(() => {
          console.log('重置失败')
        })
    },

    // 多选框选中数据
    // eslint-disable-next-line vue/no-dupe-keys
    handleSelectionChange(selection) {
      this.selectUserData = selection[0]
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    /* 删除按钮操作*/
    handleDelete(row) {
      const userIds = row.userId || this.ids
      this.$confirm('是否确认删除字典编号为"' + userIds + '"的数据项？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.axios.delete('/sysUser/' + userIds).then(res => {
            this.loadUsersList(this.current)
            this.$message({
              type: 'success',
              message: '删除成功'
            })
          })
        })
        .catch(() => {
          console.log('删除失败')
        })
    },
    /* 导入*/
    handleImport() {
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /* 下载模板操作 */
    importTemplate() {
      window.open('http://localhost:8080/sysUser/downloadTemp?Authorization=' + getToken(), '_parent')
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.loadUsersList(this.current)
    },
    // 提交上传文件
    submitFileForm() {
      console.log('提交')
      this.$refs.upload.submit()
    },
    querySysRoleList() {
      const params = `current=1&size=9999&status=0`
      this.axios.get(`/sysRole/roleList/?${params}`).then((res) => {
        this.sysRoleList = res.data.data.records
      })
    },
    // 多选中禁用一行
    selectHandle(row) {
      return !(row.userName === 'admin')
    }
  }
}
</script>

<style scoped>
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }

  .el-aside {
    color: #333;
  }
</style>
